#include <assert.h>
#include <time.h>

#include "WLogInterface.h"
#include "Common.h"

namespace WLog
{
    bool bTrimFileName = 0;

	ILogProcess* log = 0;
    
	ILogProcess* setLog(ILogProcess* pLog)
	{
		ILogProcess* pBak = log;
		log = pLog;
		return pBak;
	}

	ILogProcess* getLog()
	{
		return log;
	}	
	
	IOuter* setOuter(IOuter *pOuter)
	{
		assert(getLog());
		return getLog()->setOuter(pOuter);
	}

    ILogProcess* setOuterLog(IOuter *pOuter, ILogProcess* pLog)
    {
        ILogProcess* pBak = log;
        log = pLog;
        assert(!log->setOuter(pOuter));
        return pBak;
    }

	bool setOutLevel(int iOutLevel /*= W_LEVEL_FLOOR*/)
	{
		if (log)
		{
			log->setOutLevel(iOutLevel);
			return true;
		}
		
		return false;
	}

    bool setTrimFileName(bool bTrim)
    {
        bool bRet = bTrimFileName;
        bTrimFileName = bTrim;
        return bRet;
    }

    string buildFileNameNow(const char* szPrefix /*= ""*/, const char* szEnd /*= ".log"*/, const char* szFormatDateTime /*= "%Y-%m-%d_%H%M%S"*/)
    {
#define _TIME_MAX_BUF_SIZE 256
        char* pBuf = new char[_TIME_MAX_BUF_SIZE];
        time_t time = now_time_t();
#ifdef MORE_AND_EQUAL_THAN_VC8_VS2005
        tm timeinfo = {0};
        localtime_s(&timeinfo, &time);
        tm* tLocalTime = &timeinfo;
#else
        tm* tLocalTime = localtime(&time);
#endif // MORE_AND_EQUAL_THAN_VC8_VS2005

        strftime(pBuf, _TIME_MAX_BUF_SIZE, szFormatDateTime, tLocalTime);
        
        string strRet = szPrefix;
        strRet += pBuf;
        strRet += szEnd;
        delete [] pBuf;
        
        return strRet;
    }
}
